<template>
  <div class="create-chart-config">
    <Title title="图表名称" style="margin-bottom: 16px;">
      <span style="color: red; margin: 3px 0 0 2px;">*</span>
    </Title>
    <el-form ref="formDataRef" :model="dataForm" :rules="formRules" style="margin-bottom: 32px;" label-position="right" label-width="0px">
      <el-form-item prop="name" class="name">
        <el-input
          v-model.trim="dataForm.name"
          :maxlength="20"
          class="width240"
          size="small"
          placeholder="请填写图表名称"
          name="name"
          type="text"/>
      </el-form-item>
    </el-form>
    <!-- 选择数据表 -->
    <div class="create-chart-config-item">
      <div class="flex-center" style="margin-bottom: 16px;">
        <div><Title title="选择数据表" /></div>
        <div class="tip">请选择需要统计的数据表</div>
      </div>
      <div class="form-item">
        <selectWithoutHttp
          :disabled="isOpenLink"
          v-model="dataForm.dataSheet"
          :list-data="dataSheetOptions"
          key-name="id"
          class="width240"
          placeholder="请选择数据表"
          label-name="name"
          filterable
          clearable
          @change="dataSheetChange($event)"
        />
        <div v-if="dataForm.dataSheet" class="button-text" style="margin-left: 10px;line-height: 32px;" @click="switchLink">{{ isOpenLink?'取消关联表':'添加关联表' }}</div>
      </div>
      <div v-if="isOpenLink" class="form-item">
        <div class="label">选择关联字段</div>
        <selectWithoutHttp
          v-model="dataForm.linkFieldName"
          :list-data="dataSheetFieldList"
          key-name="name"
          class="width240"
          placeholder="选择关联字段"
          label-name="name"
          filterable
          clearable
          @change="linkFieldNameChange($event)"
        />
        <selectWithoutHttp
          v-model="dataForm.linkDataSheet"
          :list-data="linkDataSheetOptions"
          :collapse-tags="false"
          style="margin-left: 10px;"
          class="width-long"
          extend-class="width-long-item"
          placeholder="选择关联数据表"
          key-name="id"
          label-name="name"
          filterable
          multiple
          clearable
          @change="linkDataSheetFieldChange($event)"
        />
      </div>
    </div>
    <!-- 选择统计字段 -->
    <div v-if="dataForm.dataSheet" class="create-chart-config-item">
      <div class="flex-center" style="margin-bottom: 18px;">
        <div><Title title="选择统计字段" /></div>
        <div class="button-text flex-center" style="margin-left:16px;" @click="openFormulaDialog"><i class="el-icon-plus"/> 配置公式字段</div>
      </div>
      <div v-if="isCombo" class="form-item">
        <div class="label">数据指标1</div>
        <div class="yAxis-field">
          <selectWithoutHttp
            v-model="dataForm.yAxisCombo"
            :list-data="handelField(fieldList, 'yAxis')"
            :multiple="false"
            :unit-params="{
              field: 'sourceName',
            }"
            class="width-long"
            placeholder="选择数据指标1"
            key-name="uniqueId"
            label-name="name"
            foot="sourceName"
            extend-class="width-long-item"
            filterable
            clearable
          />
        </div>
      </div>
      <div class="form-item">
        <div class="label">{{ isCombo ? '数据指标2' : '数据指标' }}</div>
        <div class="yAxis-field ">
          <selectWithoutHttp
            v-if="!hideYAxisShow"
            v-model="dataForm.yAxis"
            :list-data="handelField(fieldList, 'yAxis')"
            :collapse-tags="false"
            :multiple="dataForm.type !== 13"
            :placeholder="`选择数据指标${isCombo?'2':''}`"
            :unit-params="{
              field: 'sourceName',
            }"
            key-name="uniqueId"
            class="width-long"
            label-name="name"
            extend-class="width-long-item"
            filterable
            clearable
          />
        </div>
      </div>
      <div class="form-item">
        <div class="label">数据维度</div>
        <selectWithoutHttp
          v-model="dataForm.xAxis"
          :list-data="handelField(fieldList, 'xAxis')"
          :unit-params="{
            field: 'sourceName',
          }"
          key-name="uniqueId"
          class="width-long"
          extend-class="width-long-item"
          placeholder="选择数据维度"
          label-name="name"
          filterable
          clearable
        />
      </div>
      <!-- 选择按天展示或按月展示 -->
      <div v-if="showContrastSelect || showContrastTime" class="form-item">
        <div class="label">对比日期</div>
        <el-select
          v-if="showContrastSelect"
          v-model="dataForm.contrastTime"
          size="small"
          placeholder="请选择"
          class="width240"
          popper-class="global-select-down">
          <el-option
            v-for="item in contrastTimeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id" />
        </el-select>
        <el-date-picker
          v-if="showContrastTime"
          v-model="dataForm.contrastTimeRange"
          :clearable="true"
          :editable="false"
          class="width240"
          size="small"
          type="daterange"
          placeholder="开始日期"
          value-format="timestamp"
          format="yyyy/MM/dd" />
      </div>
      <div v-if="showDataType" class="form-item">
        <div class="label"/>
        <el-radio-group v-model="dataForm.dataShowType" class="dataShowType-class">
          <el-radio :label="'按天展示'">按天展示</el-radio>
          <el-radio :label="'按月展示'">按月展示</el-radio>
        </el-radio-group>
      </div>
    </div>
    <template v-if="dataForm.dataSheet && dataForm.yAxis && dataForm.xAxis && dataForm.yAxis.length">
      <div class="create-chart-config-item">
        <FilterGroup
          v-model="dataForm.chartFilter"
          :math-options="mathOptions"
          :is-draggable="true"
          :has-data-source="dataForm.hasDataSource"
          :field-chidren-list="filterGroupFieldList"
          true
          @changeData="changeData">
          <div class="form-item">
            <div class="label">是否作为数据源</div>
            <div class="flex-center" style="height: 30px;">
              <el-switch
                v-model="dataForm.hasDataSource"
                class="fb-switch"
                @change="switchChange"
              />
            </div>
          </div>
        </FilterGroup>
      </div>
      <!-- 更多设置 -->
      <div class="create-chart-config-item">
        <Title style="margin-bottom: 18px;" title="更多设置" />
        <div class="form-item">
          <div class="label">排序</div>
          <div class="flex-center">
            <div class="flex-center" style="height: 30px;">
              <el-switch v-model="dataForm.isOrder" class="fb-switch" />
            </div>
            <div v-if="dataForm.isOrder" class="select-sort">
              <!-- 当前选择的字段 -->
              <el-select
                v-model="dataForm.sortFieldName"
                size="small"
                placeholder="字段"
                popper-class="global-select-down"
                name="sortField">
                <el-option
                  v-for="item in fieldList"
                  :key="item.uniqueId"
                  :label="item.name+`${item.sourceName?`（${item.sourceName}）`:''}`"
                  :value="item.uniqueId" />
              </el-select>
              <el-select
                v-model="dataForm.sortType"
                placeholder="展示排序"
                size="small"
                popper-class="global-select-down"
                name="sortType">
                <el-option
                  v-for="item in sortOpt"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" />
              </el-select>
              <el-input
                v-model="dataForm.showNums"
                type="number"
                oninput="if(value || value === 0) {if(value>999999999)value=999999999;if(value<1)value=1;}"
                class="input-align-left"
                size="small"
                placeholder="展示数量" />
              <el-select
                v-model="dataForm.sortShowType"
                size="small"
                placeholder="数据排序"
                popper-class="global-select-down"
                name="sortShowType">
                <el-option
                  v-for="item in sortShowTypeOpt"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" />
              </el-select>
            </div>
          </div>
        </div>
        <div class="form-item">
          <div class="label">
            <div class="flex-center">
              设置拆分字段
              <tipIcon content="可对数据维度进行字段内容拆分。请输入拆分字段的标识。" />
            </div>
          </div>
          <div class="flex-center" style="height: 30px;">
            <el-switch
              v-model="dataForm.isSplitChunk"
              class="fb-switch mr10"
            />
            <el-input
              v-if="dataForm.isSplitChunk"
              v-model="dataForm.chunkSeparator"
              :maxlength="10"
              type="text"
              class="input-align-left"
              size="small"
              placeholder="请输入拆分标识" />
          </div>
        </div>
        <div class="form-item">
          <div class="label">定时更新</div>
          <div class="flex-center" style="height: 30px;">
            <el-switch
              v-model="dataForm.isUpdateRegularly"
              class="fb-switch"
            />
            <el-select
              v-if="dataForm.isUpdateRegularly"
              v-model="dataForm.updateRegularlyType"
              placeholder="请选择"
              size="small"
              class="select-updateRegularlyType"
              popper-class="global-select-down"
              name="sortType">
              <el-option
                v-for="item in updateRegularlyOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <div class="label">是否展示</div>
          <div class="flex-center" style="height: 30px;">
            <el-switch
              v-model="dataForm.isShow"
              class="fb-switch"
            />
          </div>
        </div>
      </div>
    </template>
    <formulaDialog
      ref="formulaDialog"
      :is-show-save-word="true"
      :is-quote-template-field="false"
      @setCombFields="setCombFields" />
  </div>
</template>

<script>
import { getDataTable } from '@/api/reportManage';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import formulaDialog from '@/components/ReportManage/formulaDialog';
import Title from '@/components/Title';
import { updateRegularlyOptions } from '@/components/ReportManage/chartCreate/module/selectData.js';
import FilterGroup from '@/components/ReportManage/filterGroup';
import Contrast from '@/components/ReportManage/chartCreate/mixins/contrast';

export default {
  components: { Title, selectWithoutHttp, formulaDialog, FilterGroup },
  mixins: [Contrast],
  model: {
    prop: 'dataForm',
    event: 'changeData'
  },
  props: {
    dataForm: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      updateRegularlyOptions,
      sortOpt: [{ id: 1, name: '正序' }, { id: 2, name: '倒序' }],
      sortShowTypeOpt: [{ id: 1, name: '升序' }, { id: 2, name: '降序' }],
      isOpenLink: false, // 是否开启关联表
      dataSheetOptions: [], // 数据表
      linkDataSheetOptions: [], // 关联数据表
      mathOptions: [],
      dataSheetFieldList: [], // 所选择数据表的所有字段
      linkDataSheetFieldList: [], // 关联数据表的所有字段
      hideYAxisShow: false,
      callback: null,
      formRules: {
        name: [{ required: true, trigger: 'blur', message: '请填写图表名称' }]
      }
    };
  },
  computed: {
    fieldList() {
      const dataSheetFieldList = this.dataSheetFieldList || [];
      const linkDataSheetFieldList = this.linkDataSheetFieldList || [];
      const formulaFieldList = this.dataForm.combFields || []; // 公式字段列表
      // 合并
      return _.unionBy(dataSheetFieldList, linkDataSheetFieldList, formulaFieldList, 'uniqueId');
    },
    filterGroupFieldList() {
      const dataSheetFieldList = this.dataSheetFieldList;
      const linkDataSheetFieldList = this.linkDataSheetFieldList;
      // 合并
      return _.unionBy(dataSheetFieldList, linkDataSheetFieldList, 'uniqueId');
    },
    isCombo() { // 是否复合图形
      const type = this.dataForm.type;
      const combIds = [9, 10, 11, 12];
      return combIds.includes(type);
    },
    showDataType() {
      const dataForm = this.dataForm;
      const cur = this.fieldList.find(i => i.uniqueId === dataForm.xAxis);
      let isTimeField = false;
      // 字段的字段类型 optionsType  0:文本型 1:  时间日期  2: 数值型   3: 部门
      if (cur && cur.optionsType === 1) {
        isTimeField = true;
      }
      const showChart = [1, 2, 4, 5, 9, 10, 11, 13];
      // 1:柱状图 2:折线图 4:条型图 5:面积图 9:折线-柱状图 10:折线-折线图 11: 折线-条型图 13: 折线对比图
      const showType = dataForm.xAxis && isTimeField && showChart.includes(dataForm.type);
      if (showType && this.dataForm.dataShowType === '') {
        this.$set(this.dataForm, 'dataShowType', '按天展示');
      }
      return showType;
    }
  },
  watch: {
    'dataForm.type'(newV, oldV) {
      // const arr = [9, 10, 11, 12];
      // const isCombo = (arr.indexOf(newV) !== -1);
      // const oldIsCombo = (arr.indexOf(oldV) !== -1);
      // 切换为非组合时 清空
      // if (!isCombo) {
      //   this.dataForm.yAxisCombo = '';
      // }
      // if (isCombo !== oldIsCombo) {
      //   this.dataForm.yAxisCombo = '';
      // }
      this.hideYAxisShow = true;
      this.changeData();
      this.$nextTick(() => {
        this.hideYAxisShow = false;
      });
    }
  },
  created() {
    this.chartId = this.$route.params.id || null;
    // 选择统计字段未完成，x轴选择时间时
    this.getOptions();
  },
  methods: {
    setDefault(data) {
      if (this.contrastChange) {
        this.contrastChange();
      }
      if (this.dataForm.linkFieldName) {
        this.dataForm.linkDataSheet = this.dataForm.linkDataSheet || [];
        this.isOpenLink = true;
      }
      if (this.dataForm.combFields) {
        this.dataForm.combFields.forEach(i => {
          i.uniqueId = i.name;
        });
      }
      this.getOptions(false, this.dataForm.linkFieldName);
      this.callback = () => {
        // 重新计算关联数据表的所有字段
        if (this.dataForm.linkDataSheet && this.dataForm.linkDataSheet.length) {
          const linkDataSheet = this.dataForm.linkDataSheet;
          let list = [];
          linkDataSheet.forEach(i => {
            const dataSheetItem = this.dataSheetOptions.find(j => j.id === i);
            dataSheetItem.field.forEach(j => {
              j.sourceId = i;
            });
            list = list.concat(dataSheetItem.field || []);
          });
          this.linkDataSheetFieldList = list;
        }
        // 重新计算所选择数据表的所有字段
        if (this.dataForm.dataSheet) {
          const dataSheetItem = this.dataSheetOptions.find(i => i.id === this.dataForm.dataSheet);
          this.dataSheetFieldList = dataSheetItem.field;
          this.dataSheetFieldList.forEach(i => {
            i.sourceId = this.dataForm.dataSheet;
          });
        }
        this.callback = null;
      };
      if (this.dataSheetOptions && this.dataSheetOptions.length) {
        this.callback();
      }
    },
    switchLink() {
      this.isOpenLink = !this.isOpenLink;
      if (!this.isOpenLink) {
        this.$set(this.dataForm, 'linkDataSheet', []);
        this.$set(this.dataForm, 'linkFieldName', '');
        this.linkDataSheetOptions = [];
        this.linkDataSheetFieldList = [];
        this.checkField();
      }
    },
    /**
     * change 事件
     */
    // 数据表改变
    dataSheetChange(id) {
      const dataSheetItem = this.dataSheetOptions.find(i => i.id === id);
      this.dataSheetFieldList = dataSheetItem.field;
      this.$set(this.dataForm, 'linkDataSheet', []);
      this.$set(this.dataForm, 'linkFieldName', '');
      this.$set(this.dataForm, 'chartFilter', [{
        filterName: '筛选组1', system: []
      }]);
      this.checkField();
    },
    // 关联字段改变
    linkFieldNameChange() {
      this.$set(this.dataForm, 'linkDataSheet', []);
      this.$set(this.dataForm, 'chartFilter', [{
        filterName: '筛选组1', system: []
      }]);
      this.getOptions(false, this.dataForm.linkFieldName);
      this.checkField();
    },
    // 关联数据表改变
    linkDataSheetFieldChange(data) {
      const linkDataSheet = this.dataForm.linkDataSheet;
      let list = [];
      linkDataSheet.forEach(i => {
        const dataSheetItem = this.dataSheetOptions.find(j => j.id === i);
        list = list.concat(dataSheetItem.field || []);
      });
      this.linkDataSheetFieldList = list;
      this.$set(this.dataForm, 'chartFilter', [{
        filterName: '筛选组1', system: []
      }]);
      this.checkField();
    },
    checkField() {
      this.dataForm.yAxis = this.dataForm.type === 13 ? '' : [];
      this.dataForm.xAxis = '';
      this.dataForm.yAxisCombo = '';
      this.changeData();
    },
    // 公式字段
    openFormulaDialog() {
      this.$nextTick(() => {
        this.$refs.formulaDialog.editOpenDialog(this.dataForm.combFields || [], this.dataForm.isSave || false);
      });
    },
    setCombFields(combFieldsParams) {
      combFieldsParams.combFields.forEach(i => {
        i.uniqueId = i.name;
      });
      this.dataForm.combFields = JSON.parse(JSON.stringify(combFieldsParams.combFields));
      this.dataForm.isSave = combFieldsParams.isSave;
      if (this.dataForm.type !== 13 && combFieldsParams.combFields && combFieldsParams.combFields.length) {
        // bug-8407提出的：需要编辑数据指标，后续再删除注释
        this.dataForm.yAxis = combFieldsParams.combFields.map(item => {
          return item.name;
        });
        // bug-6540提出的需求：需要新增数据指标
        /* combFieldsParams.combFields.forEach(i => {
          if (!this.dataForm.yAxis) {
            this.dataForm.yAxis = [i.name];
          } else if (!this.dataForm.yAxis.includes(i.name)) {
            this.dataForm.yAxis.push(i.name);
          }
        }); */
      }
      this.changeData();
    },
    deleteCombFIelds(tag, index) {
      this.$refs.formulaDialog.deleteCombFIelds(tag, index);
    },
    /**
     * 数据
     */
    getOptions(init = true, fieldName = '') {
      getDataTable({ fieldName, chartId: this.chartId }).then(res => {
        if (res.data) {
          if (init) {
            res.data.condition.forEach(i => {
              if (i.field) {
                i.field.forEach(j => {
                  j.sourceId = i.id;
                  j.sourceName = i.name;
                  if (!j.uniqueId) {
                    j.uniqueId = `${j.name}#${j.sourceId}`;
                  }
                });
              }
            });
            this.dataSheetOptions = res.data.condition;
            this.mathOptions = res.data.mathOptions;
            if (this.callback) {
              this.callback();
            }
          } else {
            this.linkDataSheetOptions = fieldName === '' ? [] : res.data.condition;
          }
        }
      });
    },
    // 过滤字段列表 type yAxis: y轴字段，只能选择数值类型和公式类型  xAxis: 时间，文本，部门
    handelField(list, type) {
      // 字段的字段类型 optionsType  0:文本型 1:  时间日期  2: 数值型   3: 部门
      return list.filter(i => {
        return type === 'yAxis' ? i.optionsType === 2 || i.optionsType === undefined : i.optionsType !== 2 && i.optionsType !== undefined;
      });
    },
    submitField() {
      const yAxisCombo = this.dataForm.yAxisCombo;
      const yAxis = this.dataForm.yAxis;
      const xAxis = this.dataForm.xAxis;
      if (!this.isCombo) {
        this.dataForm.yAxisCombo = '';
      }
      const selectField = [];
      const fieldList = [];
      if (xAxis && !fieldList.includes(xAxis)) {
        fieldList.push(xAxis);
      }
      if (yAxisCombo && !fieldList.includes(yAxisCombo)) {
        fieldList.push(yAxisCombo);
      }
      if (yAxis) {
        if (typeof yAxis === 'string' && !fieldList.includes(yAxis)) {
          fieldList.push(yAxis);
        }
        if (Array.isArray(yAxis) && yAxis.length) {
          yAxis.forEach(i => {
            if (!fieldList.includes(i)) fieldList.push(i);
          });
        }
      }

      fieldList.forEach(i => {
        const cur = this.filterGroupFieldList.find(j => j.uniqueId === i);
        if (cur) {
          cur.fieldName = cur.name;
          if (this.getNameFromUniqueId(xAxis) === cur.fieldName) cur.uniqueFlag = 1;
          selectField.push(cur);
        }
      });
      if (!this.showDataType) {
        this.dataForm.dataShowType = '';
      } else if (this.dataForm.dataShowType === '') {
        this.dataForm.dataShowType = '按天展示';
      }
      selectField.forEach(i => {
        i.sourceId = i.sourceId || 0;
      });

      this.dataForm.selectField = selectField;

      this.handelParams(this.dataForm);
      this.changeData();
    },
    changeData() {
      this.$emit('changeData', this.dataForm);
      if (this.contrastChange) this.contrastChange();
    },
    validate() {
      // 提供给父组件来验证完整性
      return new Promise((resolve, reject) => {
        this.$refs.formDataRef.validate(valid => {
          if (valid) {
            resolve(valid);
          } else {
            reject();
          }
        });
      });
    },
    getNameFromUniqueId(uniqueId) {
      if (!uniqueId) return uniqueId;
      if (Array.isArray(uniqueId)) {
        return uniqueId.map(i => {
          if (i.indexOf('#') < 0) return i;
          return i.split('#')[0];
        });
      }
      if (uniqueId.indexOf('#') < 0) return uniqueId;
      // uniqueId 的格式为 ${name}#${sourceId}
      return uniqueId.split('#')[0];
    },
    switchChange(val) {
      if (val && this.dataForm.chartFilter.length > 1) {
        this.dataForm.hasDataSource = false;
        this.$message.error('作为数据源，数据筛选组仅能设置一组');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.create-chart-config {
  margin-top: 16px;
  .one-cell {
    display: flex;
  }
  .tip {
    color: #999;
    font-size: 12px;
    margin-left: 10px;
  }
}
.form-item {
  display: flex;
  margin-bottom: 24px;
  .label {
    text-align: right;
    font-size: 14px;
    color: #666;
    margin-right: 10px;
    width: 100px;
    line-height: 32px;
  }
}
.flex-center {
  display:flex;align-items:center;
}
.width-long {
  flex: 1;
  max-width: 565px;
  min-width: 240px;
  &::v-deep {
    .el-select, .el-input, .el-input__inner {
      width: 100%;
    }

  }
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
.input-align-left {
  width: 130px;
  &::v-deep {
    .el-input__inner {
      text-align: left;
    }
  }
}

.create-chart-config-item {
  margin-bottom: 32px;
}
 .select-sort {
  display: flex;
  &::v-deep {
    .el-input {
      width: 120px !important;
      margin-left: 10px;
    }
    .el-input__inner {
      width: 120px !important;
    }
  }
}
.mr10 {
  margin-right: 10px;
}
.select-updateRegularlyType {
  width: 120px;
  margin-left: 10px;
  .el-input__inner {
    width: 120px !important;
  }
}
.yAxis-field {
  display: flex;
  flex-direction: column;
  flex: 1;
  &.has-combFields {
    &::v-deep {
      .el-select {
        .el-input__inner {
          border-bottom: none;
          border-bottom-left-radius: 0;
          border-bottom-right-radius: 0;
          border-color: #DCDFE6 !important;
        }
      }
    }
  }
  .comb-fields-container {
    width: 100%;
    max-width: 565px;
    min-width: 240px;
    min-height: 32px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 0 8px;
    border: 1px solid #DCDFE6;
    border-top: none;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    &::v-deep {
      .el-tag  {
        background: #F4F7FF;
        border: none;
        color:#333333;
        margin: 2px 0;
        font-size: 14px;
        .el-icon-close {
          color: #333;
          font-size: 16px;
          &:hover {
            background:transparent
          }
        }
      }
    }
    .combFields-tag {
      background:#FFF9F2;
      color:#FD8546;
      margin-right: 10px;
      cursor:pointer;
      transition: none;
    }
  }
}
</style>
<style lang="scss" >
.width-long-item {
  .el-select-dropdown__item {
    max-width: 100%;
  }
}
</style>
